package day1220_test;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;

public class Server {
    //2.ClientService: 接收客户端的数据，用集合给每个客户端返回数据
    ArrayList<PrintWriter> allOut=new ArrayList<>();
    class ClientService  extends   Thread{
        Socket   socket;
        ClientService(Socket s){//1.服务端线程里边保存Socket(输入流和输出流)
            socket=s;
        }
        public void run(){
            try {
                PrintWriter pw=new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
                synchronized (allOut){
                    allOut.add(pw);
                }

                //2.socket获取输入流
                BufferedReader br=new BufferedReader(new InputStreamReader(socket.getInputStream()));
                String msg=null;//3.用输入流读取数据
                while(  (msg=br.readLine())!=null  ){
                    System.out.println(socket.getInetAddress()+"::"+msg);
                    //从allOut获取每个输出流，将读取的数据msg发给每个客户端
                    synchronized (allOut){
                        for(PrintWriter printw:allOut){
                            printw.println(msg);
                            printw.flush();
                        }
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    public void start() throws IOException {
        //2.创建线程，启动线程(读取客户端的数据，用集合中每个输出流返回给每个客户端)
        while(true){
            Socket s=ss.accept();///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            ClientService  cs=new ClientService(s);////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            cs.start();
        }
    }


    ServerSocket  ss;//1.
    Server() throws IOException {//1.
        ss=new ServerSocket(8088);
    }


    public static void main(String[] args) throws IOException {
        Server s=new Server();//1.构造(开启端口，等待客户端连接)
        s.start();//2.start():开启线程     接收  发送每个客户端数据
    }
}


